package cn.kuick.match3.test4;

import java.util.Stack;

public class DecodeString {

	public static void merge(Stack<String> stack) {
		
		Stack<String> texts = new Stack<String>();
		
		while(stack.size()>0) {
			String text = stack.pop();
			
			if (!isNumber(text)) {
				texts.push(text);
			} else {
				stack.push(text);
				break;
			}
		}
		
		StringBuffer result = new StringBuffer();
		
		while(texts.size()>0) {
			String ddd = texts.pop();
			result.append(ddd);
		}
		
		stack.push(result.toString());
	}
	
	public static boolean isNumber(String text) {
		try {
			Integer.parseInt(text);
			return true;
		} catch(NumberFormatException e) {
			return false;
		}
	}
	
	public static void repeat(Stack<String> stack) {
		String text = stack.pop();
		String repeat = stack.pop();
		
		StringBuffer result = new StringBuffer();
		int num = Integer.parseInt(repeat);
		
		for(int i=0; i<num; i++) {
			result.append(text);
		}
		
		stack.push(result.toString());
	}
	
	
	public static String decode(String text) {
		Stack<String> stack = new Stack<String>();
		
		StringBuffer num = new StringBuffer();
		StringBuffer word = new StringBuffer();
		
		for(int i=0; i<text.length(); i++) {
			char ch = text.charAt(i);
			
			if ('0'<=ch && ch<='9') {
				if (word.length()>0) {
					stack.push(word.toString());
					word.setLength(0);
				}
				
				num.append(ch);
			} else if (ch == '['){
				if (num.length()>0) {
					stack.push(num.toString());
					num.setLength(0);
				}
			} else if (ch == ']') {
				if (word.length()>0) {
					stack.push(word.toString());
					word.setLength(0);
				}
				
				merge(stack);
				repeat(stack);
			} else {
				word.append(ch);
			}
		}
		
		if (word.length()>0) {
			stack.push(word.toString());
			word.setLength(0);
		}
		
		merge(stack);
		
		return stack.pop();
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println(decode("2[a3[bc]]fg2[e]"));
		System.out.println(decode("fg3[ab]c2[d2[e]]"));
	}

}
